/*
 * Written by edhong Jan. 2008
 *  sample arithmetic ENCODER using QccPack,
 * based  mostly from QccENTArithmeticEncode documentation  
 *
 * This file is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 * 
 * This file is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 * 
 * 
 */

#include "libQccPack.h" 
#define FIRST_CONTEXT 0 
#define SECOND_CONTEXT 1 
#define BLOCK_LENGTH 1
#define SYMBOL_STREAM_LENGTH 12

/* this function is for  making the error checking in main more readable */
void checkerror(int error, const char *message) {
  if (error) {
    char errormessage[1000];
    snprintf(errormessage, 1000, "Error Calling %s()", message); 
    QccErrorAddMessage(errormessage);
    QccErrorExit(); 
  } 
}

int  main(int argc, char *argv[]) 
{ 
  /* let us encode the following array, switching between 
     the two contexts all the time. 
     values in FIRST_CONTEXT must be 0 or 1, while
     values in SECOND_CONTEXT can be from 0 up to 9 */
 int symbol_stream[SYMBOL_STREAM_LENGTH] = 
   {0, 7, 1, 6, 1, 7, 1, 1, 1, 2, 0, 5}; 
 /* int num_contexts = 2; */
 int num_symbols[2] = {2, 10};  
 char filename[] = "arithtest.bits";

  QccBitBuffer output_buffer; 
  QccENTArithmeticModel *model = NULL; 

  QccInit(argc, argv); 
  QccBitBufferInitialize(&output_buffer); 
  QccConvertToQccString(output_buffer.filename, filename);

  output_buffer.type = QCCBITBUFFER_OUTPUT; 
  checkerror(QccBitBufferStart(&output_buffer), "QccBitBufferStart"); 
  
  model = QccENTArithmeticEncodeStart(num_symbols, 
				      2, 
				      NULL, 
				      QCCENT_ANYNUMBITS); 
  checkerror(model == NULL, "QccENTArithmeticEncodeStart");

  printf("Encoding into %s..\n", filename);

  int counter;
  int errorvalue; 
  for (counter = 0; counter < SYMBOL_STREAM_LENGTH; counter++) {

    if (counter %2 == 0) 
      errorvalue = QccENTArithmeticSetModelContext(model, FIRST_CONTEXT);
    else 
      errorvalue = QccENTArithmeticSetModelContext(model, SECOND_CONTEXT);
    checkerror(errorvalue, "QccENTArithmeticSetModelContext");
 
    checkerror(QccENTArithmeticEncode(&symbol_stream[counter], 
				      BLOCK_LENGTH, 
				      model, 
				      &output_buffer), 
	       "QccENTArithmeticEncode"); 
    
    printf("%d ", symbol_stream[counter]);
  }
  
  printf("\n");
  checkerror(QccENTArithmeticEncodeEnd(model, 
				       SECOND_CONTEXT, 
				       &output_buffer), 
	     "QccENTArithmeticEncodeEnd"); 

  checkerror(QccBitBufferEnd(&output_buffer), 
	     "QccBitBufferEnd");

  QccENTArithmeticFreeModel(model); 

  QccExit; 
} 
